package com.webank.maling.analyzer.java.processor;

import com.webank.maling.analyzer.java.context.GraphContext;
import com.webank.maling.base.model.*;
import com.webank.maling.base.util.IdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import spoon.reflect.code.CtExpression;
import spoon.reflect.code.CtFieldAccess;
import spoon.reflect.code.CtLiteral;
import spoon.reflect.code.CtVariableAccess;
import spoon.reflect.declaration.CtAnnotation;
import spoon.reflect.declaration.CtField;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
import spoon.reflect.reference.CtTypeReference;

import java.util.*;

import static com.webank.maling.analyzer.java.support.ParseSupport.getExecutableSignature;

/**
 * Spring依赖注入注解处理器
 */
@Slf4j
public class DependencyInjectionProcessor extends com.webank.maling.analyzer.java.processor.BaseProcessor<CtType<?>> {
    private final Set<String> processedTypes = new HashSet<>();
    // 存储Qualifier值与实现类的映射关系
    private final Map<String, String> qualifierToImplementation = new HashMap<>();
    // 存储类级别注解的值与类的映射关系
    private final Map<String, String> annotationValueToClass = new HashMap<>();

    @Override
    public void process(CtType<?> element) {
        try {
            String typeId = IdGenerator.generate(IdGenerator.builder()
                    .fullQualifiedName(element.getQualifiedName())
                    .isShadow(false).build());

            // 避免重复处理
            if (processedTypes.contains(typeId)) {
                return;
            }
            processedTypes.add(typeId);

            // 第一步：处理类级别的Spring注解，收集所有注解信息
            processSpringAnnotations(element, typeId);

            // 第二步：处理字段级别的依赖注入
            processFieldDependencies(element, typeId);

            // 第三步：处理方法级别的依赖注入
            processMethodDependencies(element, typeId);

        } catch (Exception e) {
            log.error("Failed to process dependency injection for type: {}", element.getQualifiedName(), e);
        }
    }

    public DependencyInjectionProcessor(GraphContext graphContext) {
        super(graphContext);
    }

    /**
     * 处理Spring相关注解
     */
    private void processSpringAnnotations(CtType<?> element, String typeId) {
        for (CtAnnotation<?> annotation : element.getAnnotations()) {
            String annotationName = annotation.getAnnotationType().getQualifiedName();

            if (isSpringComponentAnnotation(annotationName)) {

                String annotationId = IdGenerator.generate(IdGenerator.builder()
                        .fullQualifiedName(element.getQualifiedName() + "#" + annotationName)
                        .isShadow(false).build());

                // 获取注解值
                Map<String, Object> annotationValues = getAnnotationValues(annotation);

                if (log.isDebugEnabled()) {
                    log.debug("处理Spring注解 - 类: {}, 注解: {}, 注解值: {}",
                            element.getQualifiedName(), annotationName, annotationValues);
                }

                // 处理有参数的注解
                if (!annotationValues.isEmpty()) {
                    for (Map.Entry<String, Object> entry : annotationValues.entrySet()) {
                        String key = entry.getKey();
                        Object value = entry.getValue();

                        if (log.isDebugEnabled()) {
                            log.debug("处理注解参数 - 键: {}, 值: {}, 值类型: {}",
                                    key, value, value != null ? value.getClass().getSimpleName() : "null");
                        }

                        // 处理所有类型的值，只要能够转换为字符串
                        String strValue = null;
                        if (value instanceof String) {
                            strValue = (String) value;
                        } else if (value != null) {
                            strValue = value.toString();
                        }

                        if (strValue != null && !strValue.isEmpty()) {
                            if (log.isDebugEnabled()) {
                                log.debug("存储注解值映射 - {} -> {}", strValue, element.getQualifiedName());
                            }

                            // 存储常量值与实现类的映射关系
                            annotationValueToClass.put(strValue, element.getQualifiedName());

                            // 如果是接口实现类，还需要存储接口与实现类的关系
                            for (CtTypeReference<?> interfaceType : element.getSuperInterfaces()) {
                                String interfaceName = interfaceType.getQualifiedName();
                                String implementationKey = interfaceName + "#" + strValue;
                                annotationValueToClass.put(implementationKey, element.getQualifiedName());

                                if (log.isDebugEnabled()) {
                                    log.debug("存储接口实现映射 - {} -> {}", implementationKey, element.getQualifiedName());
                                }
                            }
                        }
                    }
                } else {
                    // 处理无参数的注解，使用类名作为默认值
                    String className = element.getSimpleName();
                    // 转换为小写首字母作为默认的bean名称
                    String defaultBeanName = className.substring(0, 1).toLowerCase() + className.substring(1);
                    annotationValueToClass.put(defaultBeanName, element.getQualifiedName());

                    if (log.isDebugEnabled()) {
                        log.debug("存储默认Bean名称映射 - {} -> {}", defaultBeanName, element.getQualifiedName());
                    }

                    // 如果是接口实现类，还需要存储接口与实现类的关系
                    for (CtTypeReference<?> interfaceType : element.getSuperInterfaces()) {
                        String interfaceName = interfaceType.getQualifiedName();
                        String implementationKey = interfaceName + "#" + defaultBeanName;
                        annotationValueToClass.put(implementationKey, element.getQualifiedName());

                        if (log.isDebugEnabled()) {
                            log.debug("存储接口实现映射 - {} -> {}", implementationKey, element.getQualifiedName());
                        }
                    }
                }

                // 创建注解节点
                AnnotationNode annotationNode = AnnotationNode.builder()
                        .id(annotationId)
                        .nodeType(NodeType.ANNOTATION)
                        .fullName(element.getQualifiedName() + "#" + annotationName)
                        .name(annotation.getAnnotationType().getSimpleName())
                        .type(NodeType.ANNOTATION.name())
                        .lineStart(annotation.getPosition().getLine())
                        .lineEnd(annotation.getPosition().getEndLine())
                        .branchName(config.getBranch())
                        .commitStatus("COMMITTED")
                        .lastUpdated(now())
                        .repoId(config.getProjectId())
                        .build();

                // 设置注解内容
                String annotationContent = buildAnnotationContent(annotation, annotationValues);
                annotationNode.setContent(annotationContent);

                processNode(annotationNode);

                // 添加依赖关系
                Edge dependsEdge = Edge.builder()
                        .srcId(typeId)
                        .dstId(annotationId)
                        .type(EdgeType.CONTAINS)
                        .build();
                processEdge(dependsEdge);

                // 处理注解依赖
                processAnnotationDependencies(annotation, annotationValues, annotationId);
            }
        }
    }

    /**
     * 获取注解的值
     */
    @SuppressWarnings("rawtypes")
    private Map<String, Object> getAnnotationValues(CtAnnotation<?> annotation) {
        Map<String, Object> values = new HashMap<>();

        if (log.isDebugEnabled()) {
            log.debug("获取注解值 - 注解类型: {}", annotation.getAnnotationType().getQualifiedName());
        }

        try {
            for (Map.Entry<String, CtExpression> entry : annotation.getValues().entrySet()) {
                String key = entry.getKey();
                CtExpression<?> value = entry.getValue();

                if (log.isDebugEnabled()) {
                    log.debug("处理注解参数 - 键: {}, 值类型: {}, 值: {}",
                            key, value != null ? value.getClass().getSimpleName() : "null", value);
                }

                switch (value) {
                    case CtLiteral<?> ctLiteral -> {
                        Object literalValue = ctLiteral.getValue();
                        values.put(key, literalValue);
                        if (log.isDebugEnabled()) {
                            log.debug("字面量值: {} -> {}", key, literalValue);
                        }
                    }
                    case CtFieldAccess<?> ctFieldAccess -> {
                        // 处理常量引用，如 @Controller(FlowConst.I104)
                        String extractedValue = extractFieldAccessValue(ctFieldAccess);
                        values.put(key, extractedValue);
                        if (log.isDebugEnabled()) {
                            log.debug("字段访问值: {} -> {}", key, extractedValue);
                        }
                    }
                    case CtVariableAccess<?> ctVariableAccess -> {
                        // 处理变量引用
                        String extractedValue = extractVariableAccessValue(ctVariableAccess);
                        values.put(key, extractedValue);
                        if (log.isDebugEnabled()) {
                            log.debug("变量访问值: {} -> {}", key, extractedValue);
                        }
                    }
                    case null, default -> {
                        String stringValue = value != null ? value.toString() : null;
                        values.put(key, stringValue);
                        if (log.isDebugEnabled()) {
                            log.debug("其他类型值: {} -> {}", key, stringValue);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("获取注解值时出错: {}", annotation.getAnnotationType().getQualifiedName(), e);
        }

        if (log.isDebugEnabled()) {
            log.debug("最终注解值: {}", values);
        }

        return values;
    }

    /**
     * 提取字段访问表达式的值
     */
    private String extractFieldAccessValue(CtFieldAccess<?> fieldAccess) {
        try {
            // 获取字段的声明类型
            String declaringTypeName = fieldAccess.getVariable().getDeclaringType().getQualifiedName();
            String fieldName = fieldAccess.getVariable().getSimpleName();

            // 尝试获取字段的实际值
            CtType<?> declaringType = getType(declaringTypeName);
            if (declaringType != null) {
                CtField<?> field = declaringType.getField(fieldName);
                if (field != null && field.getDefaultExpression() != null) {
                    Object defaultValue = field.getDefaultExpression();
                    if (defaultValue instanceof CtLiteral) {
                        return ((CtLiteral<?>) defaultValue).getValue().toString();
                    }
                }
            }

            // 如果无法获取实际值，返回字段名作为备选
            return fieldName;
        } catch (Exception e) {
            log.warn("提取字段访问表达式值时出错", e);
            return fieldAccess.getVariable().getSimpleName();
        }
    }

    /**
     * 提取变量访问表达式的值
     */
    private String extractVariableAccessValue(CtVariableAccess<?> variableAccess) {
        try {
            return variableAccess.getVariable().getSimpleName();
        } catch (Exception e) {
            log.warn("提取变量访问表达式值时出错", e);
            return variableAccess.getVariable().getSimpleName();
        }
    }

    /**
     * 获取类型
     */
    private CtType<?> getType(String typeName) {
        try {
            return getFactory().Type().get(typeName);
        } catch (Exception e) {
            log.warn("获取类型时出错: {}", typeName, e);
            return null;
        }
    }

    /**
     * 构建注解内容字符串
     */
    private String buildAnnotationContent(CtAnnotation<?> annotation, Map<String, Object> values) {
        StringBuilder content = new StringBuilder();
        content.append("@").append(annotation.getAnnotationType().getSimpleName());

        if (!values.isEmpty()) {
            content.append("(");
            boolean first = true;
            for (Map.Entry<String, Object> entry : values.entrySet()) {
                if (!first) {
                    content.append(", ");
                }
                content.append(entry.getKey()).append("=");
                Object value = entry.getValue();
                if (value instanceof String) {
                    content.append("\"").append(value).append("\"");
                } else {
                    content.append(value);
                }
                first = false;
            }
            content.append(")");
        }

        return content.toString();
    }

    /**
     * 处理注解参数中的依赖关系
     */
    private void processAnnotationDependencies(CtAnnotation<?> annotation, Map<String, Object> values,
                                               String annotationId) {
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            Object value = entry.getValue();
            //fixme 注解中对类的依赖，默认认为是内部类，后面可以考虑如何优化
            if (value instanceof String strValue) {
                // 检查是否是类引用
                if (strValue.contains(".")) {
                    String typeId = IdGenerator.generate(IdGenerator.builder()
                            .fullQualifiedName(strValue)
                            .isShadow(false).build());
                    Edge dependsEdge = Edge.builder()
                            .srcId(annotationId)
                            .dstId(typeId)
                            .type(EdgeType.DEPENDS_ON)
                            .dependencyType(DependencyType.USAGE)
                            .lineNumber(annotation.getPosition().getLine())
                            .build();
                    processEdge(dependsEdge);
                }
            }
        }
    }

    /**
     * 处理字段级别的依赖注入
     */
    private void processFieldDependencies(CtType<?> element, String typeId) {
        for (CtField<?> field : element.getFields()) {
            String qualifierValue = null;
            boolean hasAutowired = false;
            boolean hasResource = false;

            // 首先检查所有注解
            for (CtAnnotation<?> annotation : field.getAnnotations()) {
                String annotationName = annotation.getAnnotationType().getQualifiedName();
                if (annotationName.contains("Autowired")) {
                    hasAutowired = true;
                } else if (annotationName.contains("Resource")) {
                    hasResource = true;
                    // 获取@Resource注解的name值
                    qualifierValue = getResourceValue(annotation);
                } else if (annotationName.contains("Qualifier")) {
                    // 获取@Qualifier注解的value值
                    qualifierValue = getQualifierValue(annotation);
                }
            }

            // 如果字段有@Autowired或@Resource注解，处理依赖注入
            if (hasAutowired || hasResource) {

                String fieldId = IdGenerator.generate(IdGenerator.builder()
                        .fullQualifiedName(element.getQualifiedName() + "#" + field.getSimpleName())
                        .isShadow(false).build());

                // 创建字段节点
                FieldNode fieldNode = FieldNode.builder()
                        .id(fieldId)
                        .nodeType(NodeType.FIELD)
                        .fullName(element.getQualifiedName() + "#" + field.getSimpleName())
                        .name(field.getSimpleName())
                        .type(field.getType().getSimpleName())
                        .visibility(determineVisibility(field))
                        .isStatic(field.isStatic())
                        .lineStart(field.getPosition().getLine())
                        .lineEnd(field.getPosition().getEndLine())
                        .branchName(config.getBranch())
                        .commitStatus("COMMITTED")
                        .lastUpdated(now())
                        .repoId(config.getProjectId())
                        .build();

                processNode(fieldNode);

                // 处理字段类型依赖
                CtTypeReference<?> fieldType = field.getType();
                if (fieldType != null && !fieldType.isPrimitive()) {
                    CtType<?> typeDeclaration = fieldType.getTypeDeclaration();
                    String fieldTypeName = fieldType.getQualifiedName();
                    boolean isShadow = typeDeclaration == null || typeDeclaration.isShadow();
                    String fieldTypeId = IdGenerator.generate(IdGenerator.builder()
                            .fullQualifiedName(fieldTypeName)
                            .isShadow(isShadow).build());

                    // 添加字段类型依赖关系
                    Edge typeDependsEdge = Edge.builder()
                            .srcId(fieldId)
                            .dstId(fieldTypeId)
                            .type(EdgeType.DEPENDS_ON)
                            .dependencyType(DependencyType.INJECTION)
                            .lineNumber(field.getPosition().getLine())
                            .build();
                    processEdge(typeDependsEdge);

                    // 处理策略模式的Map注入
                    if (fieldType.getSimpleName().equals("Map")) {
                        processStrategyMapInjection(field, fieldId, fieldType);
                    }
                    // 如果存在Qualifier或Resource name，尝试建立与具体实现类的关系
                    else if (qualifierValue != null) {
                        // 记录依赖关系，等待所有类处理完成后再建立连接
                        String implementationType = findImplementationType(fieldTypeName, qualifierValue);
                        if (implementationType != null) {
                            String implementationId = IdGenerator.generate(IdGenerator.builder()
                                    .fullQualifiedName(implementationType)
                                    .isShadow(false).build());

                            // 添加与实现类的关系
                            Edge implementationEdge = Edge.builder()
                                    .srcId(fieldId)
                                    .dstId(implementationId)
                                    .type(EdgeType.INSTANCE_OF)
                                    .dependencyType(DependencyType.INJECTION)
                                    .lineNumber(field.getPosition().getLine())
                                    .build();
                            processEdge(implementationEdge);
                        } else {
                            // 记录未解析的依赖关系，等待后续处理
                            log.debug("Found unresolved dependency: {} in field {} of class {}",
                                    qualifierValue, field.getSimpleName(), element.getQualifiedName());
                        }
                    }
                }

                // 处理注解
                for (CtAnnotation<?> annotation : field.getAnnotations()) {
                    String annotationName = annotation.getAnnotationType().getQualifiedName();
                    if (annotationName.contains("Autowired") || annotationName.contains("Resource")) {

                        String annotationId = IdGenerator.generate(IdGenerator.builder()
                                .fullQualifiedName(element.getQualifiedName() + "#" + field.getSimpleName() + "#" + annotationName)
                                .isShadow(false).build());

                        // 创建注解节点
                        AnnotationNode annotationNode = AnnotationNode.builder()
                                .id(annotationId)
                                .nodeType(NodeType.ANNOTATION)
                                .fullName(element.getQualifiedName() + "#" + field.getSimpleName() + "#" + annotationName)
                                .name(annotation.getAnnotationType().getSimpleName())
                                .type(NodeType.ANNOTATION.name())
                                .lineStart(annotation.getPosition().getLine())
                                .lineEnd(annotation.getPosition().getEndLine())
                                .branchName(config.getBranch())
                                .commitStatus("COMMITTED")
                                .lastUpdated(now())
                                .repoId(config.getProjectId())
                                .build();

                        // 设置注解内容
                        if (qualifierValue != null) {
                            String paramName = annotationName.contains("Resource") ? "name" : "value";
                            annotationNode.setContent("@" + annotation.getAnnotationType().getSimpleName() + "(" + paramName + "=\"" + qualifierValue + "\")");
                        } else {
                            annotationNode.setContent(annotation.toString());
                        }

                        processNode(annotationNode);

                        // 添加注解关系
                        Edge annotationEdge = Edge.builder()
                                .srcId(fieldId)
                                .dstId(annotationId)
                                .type(EdgeType.CONTAINS)
                                .build();
                        processEdge(annotationEdge);

                        // 添加类节点与字段节点的关系
                        Edge containsEdge = Edge.builder()
                                .srcId(typeId)
                                .dstId(fieldId)
                                .type(EdgeType.CONTAINS)
                                .build();
                        processEdge(containsEdge);
                    }
                }
            }
        }
    }

    /**
     * 处理策略模式的Map注入
     */
    private void processStrategyMapInjection(CtField<?> field, String fieldId, CtTypeReference<?> fieldType) {
        try {
            // 获取Map的泛型参数
            List<CtTypeReference<?>> typeArguments = fieldType.getActualTypeArguments();
            if (typeArguments.size() == 2) {
                CtTypeReference<?> valueType = typeArguments.get(1);
                // 如果是接口类型，查找所有实现类
                if (valueType.getTypeDeclaration() != null && valueType.getTypeDeclaration().isInterface()) {
                    String interfaceName = valueType.getQualifiedName();
                    // 查找所有实现类
                    for (CtType<?> implementation : getFactory().Type().getAll()) {
                        if (implementation.isSubtypeOf(valueType)) {
                            String implementationName = implementation.getQualifiedName();
                            String implementationId = IdGenerator.generate(IdGenerator.builder()
                                    .fullQualifiedName(implementationName)
                                    .isShadow(false).build());

                            // 记录接口到实现类的映射
                            String implementationKey = interfaceName + "#" + implementation.getSimpleName();
                            qualifierToImplementation.put(implementationKey, implementationName);

                            // 创建策略实现关系边
                            Edge strategyEdge = Edge.builder()
                                    .srcId(fieldId)
                                    .dstId(implementationId)
                                    .type(EdgeType.INSTANCE_OF)
                                    .dependencyType(DependencyType.INJECTION)
                                    .lineNumber(field.getPosition().getLine())
                                    .build();
                            processEdge(strategyEdge);

                            // 创建接口实现关系边
//                            Edge implementationEdge = Edge.builder()
//                                    .srcId(implementationId)
//                                    .dstId(IdGenerator.generate(interfaceName))
//                                    .type(EdgeType.IMPLEMENTED_BY)
//                                    .dependencyType(DependencyType.IMPLEMENTATION)
//                                    .lineNumber(field.getPosition().getLine())
//                                    .build();
//                            processEdge(implementationEdge);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Failed to process strategy map injection for field: {}", field.getSimpleName(), e);
        }
    }

    /**
     * 查找实现类
     */
    private String findImplementationType(String interfaceType, String qualifierValue) {
        // 1. 首先检查是否有对应的类级别注解
        String implementationType = annotationValueToClass.get(qualifierValue);
        if (implementationType != null) {
            return implementationType;
        }

        // 2. 检查接口实现
        String interfaceKey = interfaceType + "#" + qualifierValue;
        implementationType = annotationValueToClass.get(interfaceKey);
        if (implementationType != null) {
            return implementationType;
        }

        // 3. 检查Bean方法
        return qualifierToImplementation.get(qualifierValue);
    }

    /**
     * 获取@Resource注解的name值
     */
    private String getResourceValue(CtAnnotation<?> annotation) {
        try {
            Object value = annotation.getValues().get("name");

            String simpleName = value != null ? value.getClass().getSimpleName() : "null";
            if (log.isDebugEnabled()) {
                log.debug("获取@Resource name值 - 原始值类型: {}, 值: {}",
                        simpleName, value);
            }

            switch (value) {
                case CtLiteral<?> ctLiteral -> {
                    String result = ctLiteral.getValue().toString();
                    log.debug("@Resource name值为字面量: {}", result);
                    return result;
                }
                case CtFieldAccess<?> ctFieldAccess -> {
                    // 使用与getAnnotationValues相同的逻辑
                    String result = extractFieldAccessValue(ctFieldAccess);
                    log.debug("@Resource name值为字段访问表达式，解析结果: {}", result);
                    return result;
                }
                case CtVariableAccess<?> ctVariableAccess -> {
                    // 使用与getAnnotationValues相同的逻辑
                    String result = extractVariableAccessValue(ctVariableAccess);
                    log.debug("@Resource name值为变量访问表达式，解析结果: {}", result);
                    return result;
                }
                case null, default -> {
                    log.warn("@Resource name值类型不支持: {}", simpleName);
                    return value != null ? value.toString() : null;
                }
            }
        } catch (Exception e) {
            log.warn("获取@Resource name值时出错", e);
        }
        return null;
    }

    /**
     * 获取@Qualifier注解的value值
     */
    private String getQualifierValue(CtAnnotation<?> annotation) {
        try {
            Object value = annotation.getValues().get("value");

            String simpleName = value != null ? value.getClass().getSimpleName() : "null";
            if (log.isDebugEnabled()) {
                log.debug("获取@Qualifier value值 - 原始值类型: {}, 值: {}",
                        simpleName, value);
            }

            switch (value) {
                case CtLiteral<?> ctLiteral -> {
                    String result = ctLiteral.getValue().toString();
                    log.debug("@Qualifier value值为字面量: {}", result);
                    return result;
                }
                case CtFieldAccess<?> ctFieldAccess -> {
                    // 使用与getAnnotationValues相同的逻辑
                    String result = extractFieldAccessValue(ctFieldAccess);
                    log.debug("@Qualifier value值为字段访问表达式，解析结果: {}", result);
                    return result;
                }
                case CtVariableAccess<?> ctVariableAccess -> {
                    // 使用与getAnnotationValues相同的逻辑
                    String result = extractVariableAccessValue(ctVariableAccess);
                    log.debug("@Qualifier value值为变量访问表达式，解析结果: {}", result);
                    return result;
                }
                case null, default -> {
                    log.warn("@Qualifier value值类型不支持: {}", simpleName);
                    return value != null ? value.toString() : null;
                }
            }
        } catch (Exception e) {
            log.warn("获取@Qualifier value值时出错", e);
        }
        return null;
    }

    /**
     * 处理方法级别的依赖注入
     */
    private void processMethodDependencies(CtType<?> element, String typeId) {
        for (CtMethod<?> method : element.getMethods()) {
            for (CtAnnotation<?> annotation : method.getAnnotations()) {
                String annotationName = annotation.getAnnotationType().getQualifiedName();

                if (annotationName.equals(Bean.class.getName())) {

                    String methodId = IdGenerator.generate(IdGenerator.builder()
                            .fullQualifiedName(getExecutableSignature(element.getQualifiedName(), method))
                            .isShadow(false).build());

                    String annotationId = IdGenerator.generate(IdGenerator.builder()
                            .fullQualifiedName(getExecutableSignature(element.getQualifiedName(), method) + "#" + annotationName)
                            .isShadow(false).build());

                    // 获取Bean方法的返回类型
                    CtTypeReference<?> returnType = method.getType();
                    if (returnType != null) {
                        String returnTypeName = returnType.getQualifiedName();
                        // 获取Bean名称
                        String beanName = method.getSimpleName();
                        // 检查是否有@Bean的name属性
                        Object nameValue = annotation.getValues().get("name");
                        if (nameValue instanceof CtLiteral) {
                            beanName = ((CtLiteral<?>) nameValue).getValue().toString();
                        }
                        // 存储Bean方法与返回类型的映射关系
                        qualifierToImplementation.put(beanName, returnTypeName);
                    }

                    // 创建方法节点
                    FunctionNode methodNode = FunctionNode.builder()
                            .id(methodId)
                            .nodeType(NodeType.FUNCTION)
                            .fullName(getExecutableSignature(element.getQualifiedName(),method))
                            .name(method.getSimpleName())
                            .visibility(determineVisibility(method))
                            .isStatic(method.isStatic())
                            .isConstructor(false)
                            .lineStart(method.getPosition().getLine())
                            .lineEnd(method.getPosition().getEndLine())
                            .branchName(config.getBranch())
                            .commitStatus("COMMITTED")
                            .lastUpdated(now())
                            .repoId(config.getProjectId())
                            .build();

                    processNode(methodNode);

                    // 创建注解节点
                    AnnotationNode annotationNode = AnnotationNode.builder()
                            .id(annotationId)
                            .nodeType(NodeType.ANNOTATION)
                            .fullName(getExecutableSignature(element.getQualifiedName(),method) + "#" + annotationName)
                            .name(annotation.getAnnotationType().getSimpleName())
                            .type(NodeType.ANNOTATION.name())
                            .lineStart(annotation.getPosition().getLine())
                            .lineEnd(annotation.getPosition().getEndLine())
                            .branchName(config.getBranch())
                            .commitStatus("COMMITTED")
                            .lastUpdated(now())
                            .repoId(config.getProjectId())
                            .build();

                    // 设置注解内容
                    String annotationContent = buildAnnotationContent(annotation, getAnnotationValues(annotation));
                    annotationNode.setContent(annotationContent);

                    processNode(annotationNode);

                    // 添加依赖关系
                    Edge dependsEdge = Edge.builder()
                            .srcId(methodId)
                            .dstId(typeId)
                            .type(EdgeType.DEPENDS_ON)
                            .dependencyType(DependencyType.BEAN_DEFINITION)
                            .lineNumber(method.getPosition().getLine())
                            .build();
                    processEdge(dependsEdge);

                    // 添加注解关系
                    Edge annotationEdge = Edge.builder()
                            .srcId(methodId)
                            .dstId(annotationId)
                            .type(EdgeType.CONTAINS)
                            .build();
                    processEdge(annotationEdge);
                }
            }
        }
    }

    /**
     * 判断是否为Spring组件注解
     */
    private boolean isSpringComponentAnnotation(String annotationName) {
        return annotationName.equals(Component.class.getName()) ||
                annotationName.equals(Service.class.getName()) ||
                annotationName.equals(Repository.class.getName()) ||
                annotationName.equals(Controller.class.getName()) ||
                annotationName.equals(Configuration.class.getName());
    }

    /**
     * 确定方法的可见性
     */
    private String determineVisibility(CtMethod<?> method) {
        if (method.isPublic()) {
            return "public";
        } else if (method.isPrivate()) {
            return "private";
        } else if (method.isProtected()) {
            return "protected";
        }
        return "default";
    }

    /**
     * 确定字段的可见性
     */
    private String determineVisibility(CtField<?> field) {
        if (field.isPublic()) {
            return "public";
        } else if (field.isPrivate()) {
            return "private";
        } else if (field.isProtected()) {
            return "protected";
        }
        return "default";
    }

    /**
     * 获取依赖注入相关的映射
     *
     * @return 包含qualifierToImplementation和annotationValueToClass的Map数组
     */
    public Map<String, String>[] getDependencyMaps() {
        @SuppressWarnings("unchecked")
        Map<String, String>[] maps = new HashMap[2];
        maps[0] = qualifierToImplementation;
        maps[1] = annotationValueToClass;
        return maps;
    }

    @Override
    protected Logger getLogger() {
        return log;
    }
} 